﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Threading;

using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using MINERP.DAL;
using MINERP.DAL.GenerateReports;

namespace MINERP.BLL.GenerateReports
{
    public class StatisticsBLL
    {
        /// <summary>
        /// 获得所有还未统计的orderProductID
        /// </summary>
        /// <returns></returns>
        private List<int> GetOrderProductIDHaveNotStatistics()
        {
            List<int> list = new List<int>();
            using (newSampleYPDBEntities Entites = new newSampleYPDBEntities())
            {
                string sql = string.Format("it.iscount=0 AND it.status ={0} or it.iscount is null and it.status ={0}", (int)OrderInfoStatus.Completed);
                List<orderInfo> orderList = Entites.orderInfo.Where(sql).ToList();
                foreach (var item in orderList)
                {
                    list.Add(item.OrderProductId);
                }
            }
            return list;

        }
        //public void MoveData()
        //{
        //    using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
        //    {
        //        List<Tb_OrderBag> listSource = dataBase.Tb_OrderBag.Where(ob => ob.Status == 3).ToList();

        //        MoveDataToHistroyTable(listSource, dataBase);
        //    }
        //}

      
        /// <summary>
        /// <summary>
        /// 统计
        /// </summary>
        public void Statistics()
        {
            try
            {

                string result = string.Empty;
                string[] results;
                List<int> list = GetOrderProductIDHaveNotStatistics();
                foreach (var orderProductID in list)
                {
                    //存储过程实现

                    result = StatisticsDAL.generateStatisticsReports(orderProductID);
                    results = result.Split(',');

                    for (int i = 0; i < results.Length; i++)
                    {

                        string a = results[i];
                        if (a != string.Empty)
                        {
                            if (Convert.ToInt32(a) <= 0)
                            {
                                switch (Convert.ToInt32(a))
                                {
                                    case 0:
                                        WriteLog(orderProductID, "更改产品统计状态出错");
                                        break;
                                    case -1:
                                        WriteLog(orderProductID, "员工业绩统计出错");
                                        break;
                                    case -2:
                                        WriteLog(orderProductID, "每日开单面积统计出错");
                                        break;
                                    case -3:
                                        WriteLog(orderProductID, "商户开单产品统计出错");
                                        break;
                                    default:
                                        WriteLog(orderProductID, "产品流程中用户ID为0");
                                        break;

                                }
                            }
                        }
                    }

                    //entity framework 实现
                    /*
                    using (TransactionScope tc = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                    {
                        using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
                        {

                            bool PerformanceOK = PerformanceStatistics(orderProductID, Entities);
                            bool StartOrderAreasEnveryDayOK = StartOrderAreasEnveryDayStatistics(orderProductID, Entities);
                            bool ShopProductOK = ShopProductStatistics(orderProductID, Entities);
                            bool ProductOK = ProductStatistics(orderProductID, Entities);
                            if (PerformanceOK && StartOrderAreasEnveryDayOK && ShopProductOK && ProductOK)
                            {
                                orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductID);
                                oi.isCount = 1;
                                Entities.SaveChanges();
                                tc.Complete();
                            }

                        }
                    }*/
                    //Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                WriteLog(0, ex.Message);
            }
        }
        /// <summary>
        /// 业绩统计
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <param name="Entites"></param>
        /// <returns></returns>
        private bool PerformanceStatistics(int orderProductID, newSampleYPDBEntities Entities)
        {
            bool flag = true;

            int orderNum;
            int photoNum;
            double areas;

            try
            {

                GetNumAndAreas(orderProductID, Entities, out orderNum, out photoNum, out areas);
                List<WorkOrderFlowList> workOrderFlowList = Entities.WorkOrderFlowList.Where(w => w.orderInfo.OrderProductId == orderProductID).ToList();
                foreach (var workflow in workOrderFlowList)
                {
                    users user = Entities.users.FirstOrDefault(u => u.userID == workflow.UserId);
                    if (user == null)
                        continue;
                    if (!user.tb_WorkerGroupReference.IsLoaded)
                    {
                        user.tb_WorkerGroupReference.Load();
                    }
                    string completeDatestr = workflow.CompletedTime.Value.ToShortDateString();
                    DateTime completeDate = Convert.ToDateTime(completeDatestr);
                    if (!workflow.tb_TechReference.IsLoaded)
                    {
                        workflow.tb_TechReference.Load();
                    }
                    EmployeePerformance employeePerformance = Entities.EmployeePerformance.FirstOrDefault(e => e.Tech == workflow.tb_Tech.TechName && e.UserName == user.UserName && e.CompleteDate == completeDate);
                    if (employeePerformance != null)
                    {
                        //在原有的 记录上累加面积，照片数，订单数
                        employeePerformance.OrderNum += orderNum;
                        employeePerformance.PhotoNum += photoNum;
                        employeePerformance.Areas += areas;
                        Entities.SaveChanges();

                    }
                    else
                    {
                        //新增一条记录
                        EmployeePerformance ep = new EmployeePerformance();
                        ep.Areas = areas;
                        ep.Departments = user.tb_WorkerGroup.GroupName;
                        ep.OrderNum = orderNum;
                        ep.PhotoNum = photoNum;
                        ep.CompleteDate = completeDate;
                        ep.Tech = workflow.tb_Tech.TechName;
                        ep.UserName = user.UserName;
                        Entities.AddToEmployeePerformance(ep);
                        Entities.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                flag = false;
                StringBuilder sb = new StringBuilder();
                sb.Append(DateTime.Now.ToString());
                sb.Append("  员工业绩统计时发生异常: ");
                sb.Append(ex.Message);
                WriteLogForCheck.CreateLogFile();
                WriteLogForCheck.WriteLogFile(sb);
            }

            return flag;

        }
        /// <summary>
        /// 每日开单面积统计
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <param name="Entites"></param>
        /// <returns></returns>
        private bool StartOrderAreasEnveryDayStatistics(int orderProductID, newSampleYPDBEntities Entities)
        {
            bool flag = true;
            double areas;
            if (!isReturnProduct(Entities, orderProductID))
            {
                try
                {
                    areas = GetOrderProductArea(orderProductID, Entities);
                    orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductID);
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    string orderTimeStr = oi.Tb_OrderBag.OrderTime.ToShortDateString();
                    DateTime orderTime = Convert.ToDateTime(orderTimeStr);
                    CreateOrderAreaByDay createOrder = Entities.CreateOrderAreaByDay.FirstOrDefault(c => c.CreateOrderDate == orderTime);
                    if (createOrder != null)
                    {
                        createOrder.Area += areas;
                        Entities.SaveChanges();
                    }
                    else
                    {
                        CreateOrderAreaByDay COA = new CreateOrderAreaByDay();
                        COA.Area = areas;
                        COA.CreateOrderDate = orderTime;
                        Entities.AddToCreateOrderAreaByDay(COA);
                        Entities.SaveChanges();

                    }

                }
                catch (Exception ex)
                {
                    flag = false;
                    StringBuilder sb = new StringBuilder();
                    sb.Append(DateTime.Now.ToString());
                    sb.Append("  每日开单面积统计时发生异常: ");
                    sb.Append(ex.Message);
                    WriteLogForCheck.CreateLogFile();
                    WriteLogForCheck.WriteLogFile(sb);
                }
            }
            return flag;

        }
        /// <summary>
        /// 商户开单产品
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <param name="Entites"></param>
        /// <returns></returns>
        private bool ShopProductStatistics(int orderProductID, newSampleYPDBEntities Entities)
        {
            bool flag = true;
            double areas;
            if (!isReturnProduct(Entities, orderProductID))
            {
                try
                {
                    areas = GetOrderProductArea(orderProductID, Entities);
                    orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductID);
                    if (!oi.Tb_ProductReference.IsLoaded)
                    {
                        oi.Tb_ProductReference.Load();
                    }
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                    {
                        oi.Tb_OrderBag.ShopReference.Load();
                    }
                    string orderTimeStr = oi.Tb_OrderBag.OrderTime.ToShortDateString();
                    DateTime orderTime = Convert.ToDateTime(orderTimeStr);
                    string shopName = oi.Tb_OrderBag.Shop.shopName;
                    string productName = oi.Tb_Product.ProductName;
                    string spec = oi.Tb_Product.Width.ToString() + " X " + oi.Tb_Product.Height.ToString();
                    ShopProduct shopProduct = Entities.ShopProduct.FirstOrDefault(s => s.ShopName == shopName && s.ProductName == productName && s.Spec == spec && s.OrderTime == orderTime);
                    if (shopProduct != null)
                    {
                        shopProduct.ProductNum += 1;
                        shopProduct.Area += areas;
                        Entities.SaveChanges();

                    }
                    else
                    {
                        ShopProduct sp = new ShopProduct();
                        sp.Area = areas;
                        sp.OrderTime = orderTime;
                        sp.ProductName = productName;
                        sp.ProductNum = 1;
                        sp.ShopName = shopName;
                        sp.Spec = spec;
                        Entities.AddToShopProduct(sp);
                        Entities.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    flag = false;
                    StringBuilder sb = new StringBuilder();
                    sb.Append(DateTime.Now.ToString());
                    sb.Append("  商户开单产品统计时发生异常: ");
                    sb.Append(ex.Message);
                    WriteLogForCheck.CreateLogFile();
                    WriteLogForCheck.WriteLogFile(sb);
                }
            }
            return flag;
        }
        /// <summary>
        /// 车间产品统计
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <param name="Entites"></param>
        /// <returns></returns>
        private bool ProductStatistics(int orderProductID, newSampleYPDBEntities Entities)
        {
            bool flag = true;
            return flag;
        }
        /// <summary>
        /// 计算产品的订单数，照片数，面积
        /// </summary>
        /// <param name="orderproductid"></param>
        /// <param name="orderNum"></param>
        /// <param name="photoNum"></param>
        /// <param name="areas"></param>
        public void GetNumAndAreas(int orderproductid, newSampleYPDBEntities Entities, out int orderNum, out int photoNum, out double areas)
        {
            orderNum = 0;
            photoNum = 0;
            areas = 0;

            orderInfo orderInfo = Entities.orderInfo.FirstOrDefault(o => o.OrderProductId == orderproductid);
            if (!orderInfo.Tb_OrderBagReference.IsLoaded)
            {
                orderInfo.Tb_OrderBagReference.Load();
            }
            if (!orderInfo.photoInfo.IsLoaded)
            {
                orderInfo.photoInfo.Load();
            }
            //计算订单数
            if (orderInfo.Tb_OrderBag != null)
            {
                orderNum += 1;
            }
            //计算照片张数
            if (orderInfo.photoInfo.Count > 0)
            {
                photoNum = orderInfo.photoInfo.Count;
            }
            //计算面积
            foreach (var item in orderInfo.photoInfo)
            {
                areas += item.Height * item.Width * 2.54 * 2.54 / 10000;
            }
        }
        /// <summary>
        /// 计算一个产品的面积
        /// </summary>
        /// <param name="orderproductid"></param>
        /// <param name="Entities"></param>
        /// <returns></returns>
        public double GetOrderProductArea(int orderproductid, newSampleYPDBEntities Entities)
        {
            double areas = 0;
            orderInfo orderInfo = Entities.orderInfo.FirstOrDefault(o => o.OrderProductId == orderproductid);
            if (!orderInfo.photoInfo.IsLoaded)
            {
                orderInfo.photoInfo.Load();
            }
            //计算面积
            foreach (var item in orderInfo.photoInfo)
            {
                areas += item.Height * item.Width * 2.54 * 2.54 / 10000;
            }
            return areas;

        }
        /// <summary>
        /// 是否反单产品
        /// </summary>
        /// <param name="Entities"></param>
        /// <param name="orderProductid"></param>
        /// <returns></returns>
        private bool isReturnProduct(newSampleYPDBEntities Entities, int orderProductid)
        {
            bool flag = false;
            orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductid);
            if (oi.ProductType == (int)
                ProductType.InnerReturn)
            {
                flag = true;
            }
            return flag;
        }
        /// <summary>
        /// 异常写日志
        /// </summary>
        /// <param name="orderProductid"></param>
        /// <param name="errorMessage"></param>
        private void WriteLog(int orderProductid, string errorMessage)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(DateTime.Now.ToString());
            sb.Append("  " + errorMessage + ", ");
            sb.Append(" 产品号为:" + orderProductid);
            WriteLogForCheck.CreateLogFile();
            WriteLogForCheck.WriteLogFile(sb);
        }
    }
}
